package com.quectel.core.module.forum.service.impl.mongo;

import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.constant.core.forum.ForumConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.config.TransactionManagerConfig;
import com.quectel.core.constants.MongoCollectionConstants;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.MongoAuthComponent;
import com.quectel.core.module.forum.dto.mongo.*;
import com.quectel.core.module.forum.entity.mongo.ForumCommentModel;
import com.quectel.core.module.forum.service.mongo.*;
import com.quectel.core.module.mobileuser.dto.MobileUserDto;
import com.quectel.core.module.mobileuser.service.MobileUserService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.Request;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mongo.MongodbUtils;
import com.quectel.util.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.aggregation.*;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/5/8 15:52
 * @description 帖子
 */
@DubboService
@Slf4j
public class ForumCommentServiceImpl implements ForumCommentService {

    @Autowired
    private MongoAuthComponent mongoAuthComponent;
    @Autowired
    private MobileUserService mobileUserService;
    @Autowired
    private ForumPostService forumPostService;
    @Autowired
    private ForumCommentService forumCommentService;
    @Autowired
    private ForumCommentLikeService forumCommentLikeService;
    @Autowired
    private ForumMsgService forumMsgService;
    @Autowired
    private ForumAuditRecordService forumAuditRecordService;
    @Autowired
    private ForumPersonCountService forumPersonCountService;

    private static final Function<Long, String> FORUM_COMMENT_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "FORUM_COMMENT_CACHE_BY_ID_FUNC:%d", id);

    private static final Consumer<Long> CLEAR_CACHE_FUNC = id -> {
        CacheKit.invalidRedisCache(FORUM_COMMENT_CACHE_BY_ID_FUNC.apply(id));
    };


    private Criteria sqlWhere(Map<String, Object> params) {
        Request request = Request.configParams(params);

        Criteria criteria = new Criteria();

        Long id = request.getLong(LambdaUtil.getFieldName(ForumCommentModel::getId));
        if (id != null) {
            criteria.and(SystemConstants.MONGO_ENTITY_ID_FLAG).is(id);
        }

        Long postId = request.getLong(LambdaUtil.getFieldName(ForumCommentModel::getForumPostId));
        if (postId != null) {
            criteria.and(LambdaUtil.getFieldName(ForumCommentModel::getForumPostId)).is(postId);
        }

        Long parentId = request.getLong(LambdaUtil.getFieldName(ForumCommentModel::getParentId));
        if (parentId != null) {
            criteria.and(LambdaUtil.getFieldName(ForumCommentModel::getParentId)).is(parentId);
        }

        Long personId = request.getLong(LambdaUtil.getFieldName(ForumCommentModel::getPersonId));
        if (personId != null) {
            criteria.and(LambdaUtil.getFieldName(ForumCommentModel::getPersonId)).is(personId);
        }

        Long commentPersonId = request.getLong(LambdaUtil.getFieldName(ForumCommentModel::getCommentedPersonId));
        if (commentPersonId != null) {
            criteria.and(LambdaUtil.getFieldName(ForumCommentModel::getCommentedPersonId)).is(commentPersonId);
        }

        Byte deleteFlag = request.getByte(LambdaUtil.getFieldName(ForumCommentModel::getDeletedFlag));
        if (deleteFlag != null) {
            criteria.and(LambdaUtil.getFieldName(ForumCommentModel::getDeletedFlag)).is(deleteFlag);
        }


        return new Criteria().andOperator(criteria);
    }


    private ForumCommentDto paddingField(ForumCommentDto dto) {
        if (dto != null) {
            MobileUserDto mobileUserDto = mobileUserService.selectCacheById(dto.getPersonId());
            if (mobileUserDto != null) {
                dto.setNickname(mobileUserDto.getNickname());
                dto.setHeadImg(mobileUserDto.getHeadImg());
            }

            MobileUserDto commentedUser = mobileUserService.selectCacheById(dto.getCommentedPersonId());
            if (commentedUser != null) {
                dto.setCommentedNickname(commentedUser.getNickname());
                dto.setCommentedHeadImg(commentedUser.getHeadImg());
            }
        }
        return dto;
    }

    @Override
    public void deleteByPostId(Long postId) {
        Criteria criteria = Criteria.where(LambdaUtil.getFieldName(ForumCommentModel::getForumPostId)).is(postId);
        //更新为删除状态
        Update update = new Update().set(LambdaUtil.getFieldName(ForumCommentModel::getDeletedFlag), SystemConstants.YES);
        MongodbUtils.update(new Query(criteria), update, MongoCollectionConstants.FORUM_COMMENT);
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.FORUM_COMMENT_LOCK + "#{#commentId}"
            }
    )
    @Transactional(transactionManager = TransactionManagerConfig.MONGO_TRANSACTION_MANAGER, rollbackFor = RuntimeException.class)
    public void batchLogicDeleteById(Long postId, Long commentId) {
        ForumCommentService forumCommentService = SpringUtils.getBean(ForumCommentService.class);

        ForumCommentDto targetComment = selectById(commentId);
        //不执行
        if (targetComment == null || SystemConstants.YES.equals(targetComment.getDeletedFlag())) {
            return;
        }
        //执行逻辑删除
        forumCommentService.logicDeleteById(commentId);

        //查询子集评论数据
        Map<String, Object> params = new HashMap<>();
        params.put(LambdaUtil.getFieldName(ForumCommentDto::getForumPostId), postId);
        params.put(LambdaUtil.getFieldName(ForumCommentDto::getId), commentId);
        List<ForumCommentDto> forumCommentDtos = forumCommentService.commentList(params);
        //遍历删除
        if (CollectionUtils.isNotEmpty(forumCommentDtos)) {
            forumCommentDtos.forEach(forumCommentDto -> {
                //已删除的不操作
                if (!SystemConstants.YES.equals(forumCommentDto.getDeletedFlag())) {
                    forumCommentService.logicDeleteById(forumCommentDto.getId());
                }
            });
        }

    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.FORUM_COMMENT_LOCK + "#{#id}"
            }
    )
    @Transactional(transactionManager = TransactionManagerConfig.MONGO_TRANSACTION_MANAGER, rollbackFor = RuntimeException.class)
    public void logicDeleteById(Long id) {
        ForumCommentService forumCommentService = SpringUtils.getBean(ForumCommentService.class);
        ForumCommentDto dto = selectById(id);
        if (dto == null || SystemConstants.YES.equals(dto.getDeletedFlag())) {
            return;
        }
        dto.setDeletedFlag(SystemConstants.YES);
        forumCommentService.updateById(dto);

        //更新父级非根节点评论
        if (!dto.getParentId().equals(-1L)) {
            ForumCommentDto parentComment = selectById(dto.getParentId());
            //存在
            //且未删除
            //且不是根评论
            //更新评论的评论数量
            if (parentComment != null && !parentComment.getDeletedFlag().equals(SystemConstants.YES) && !parentComment.getParentId().equals(-1L)) {
                forumCommentService.updateCommentCount(parentComment.getId(), ForumConstants.ForumHandleType.COMMENT_COMMENT.getType(), -1);
            }

            //扣减根评论
            ForumCommentDto rootComment = selectRootComment(id);
            //根评论未被删除
            if (rootComment != null && !rootComment.getDeletedFlag().equals(SystemConstants.YES)) {
                forumCommentService.updateCommentCount(rootComment.getId(), ForumConstants.ForumHandleType.POST_COMMENT.getType(), -1);
            }

        } else {
            //如果删除的是根评论,则不需要操作
        }
        //更新帖子评论数量
        forumPostService.updateForumCount(dto.getForumPostId(), ForumConstants.ForumHandleType.POST_COMMENT.getType(), -1);

        CLEAR_CACHE_FUNC.accept(id);
    }

    @Override
    @Transactional(transactionManager = TransactionManagerConfig.MONGO_TRANSACTION_MANAGER, rollbackFor = RuntimeException.class)
    public void auditDeleteBatch(Long tenantId, Long auditUserId, List<Byte> violationTypes, String remark, Long[] ids) {
        ForumCommentService forumCommentService = SpringUtils.getBean(ForumCommentService.class);
        for (Long id : ids) {
            ForumCommentDto forumCommentDto = selectById(id);
            if (forumCommentDto == null || SystemConstants.YES.equals(forumCommentDto.getDeletedFlag())) {
                continue;
            }

            forumCommentService.logicDeleteById(id);

            //新增审核记录
            ForumAuditRecordDto forumAuditRecordDto = new ForumAuditRecordDto();
            forumAuditRecordDto.setTenantId(tenantId);
            forumAuditRecordDto.setMobileUserId(forumCommentDto.getPersonId());
            forumAuditRecordDto.setSourceType(ForumConstants.ForumAuditObjectEnum.COMMENT.getType());
            forumAuditRecordDto.setSourceId(id);
            forumAuditRecordDto.setAuditUserId(auditUserId);
            forumAuditRecordDto.setResult(ForumConstants.ForumAuditResultEnum.DELETE_COMMENT.getResult());
            forumAuditRecordDto.setViolationTypes(violationTypes);
            forumAuditRecordDto.setRemark(remark);
            forumAuditRecordDto.setAuditTime(new Date());

            forumAuditRecordService.save(forumAuditRecordDto);

        }

    }

    @Override
    public void logicDeleteBatch(Long[] ids) {
        ForumCommentService forumCommentService = SpringUtils.getBean(ForumCommentService.class);
        for (Long id : ids) {
            forumCommentService.logicDeleteById(id);
        }

    }

    @Override
    public void like(Long commentId, Long userId, Byte status) {
        ForumCommentDto dto = selectById(commentId);
        //如果帖子不存在或者被删除
        if (dto == null || SystemConstants.YES.equals(dto.getDeletedFlag())) {
            return;
        }
        ForumPostDto forumPostDto = forumPostService.selectById(dto.getForumPostId());
        if (forumPostDto == null || SystemConstants.YES.equals(forumPostDto.getDeletedFlag())) {
            return;
        }

        if (SystemConstants.YES.equals(status)) {
            ForumCommentLikeDto forumCommentLikeDto = new ForumCommentLikeDto();
            forumCommentLikeDto.setForumCommentId(commentId);
            forumCommentLikeDto.setPersonId(userId);
            forumCommentLikeDto.setLikeTime(new Date());
            forumCommentLikeService.save(forumCommentLikeDto);
            //更新点赞数量
            forumCommentService.updateCommentCount(dto.getId(), ForumConstants.ForumHandleType.LIKE_COMMENT.getType(), 1);

            forumMsgService.operateSuccessNotify(forumPostDto.getTenantId(), commentId, userId, dto.getPersonId(), ForumConstants.ForumHandleType.LIKE_COMMENT.getType());

        } else if (SystemConstants.NO.equals(status)) {
            //删除点赞
            forumCommentLikeService.deleteByPostAndOperator(commentId, userId);
            //更新点赞数量
            forumPersonCountService.updateCommentCount(forumPostDto.getTenantId(), userId, ForumConstants.ForumHandleType.LIKE_COMMENT.getType(), -1);

            //删除对应的消息
            Map<String, Object> params = new HashMap<>(4);
            params.put(LambdaUtil.getFieldName(ForumMsgDto::getMobileUserId), userId);
            params.put(LambdaUtil.getFieldName(ForumMsgDto::getOperatedPersonId), userId);
            params.put(LambdaUtil.getFieldName(ForumMsgDto::getBusinessId), commentId);
            params.put(LambdaUtil.getFieldName(ForumMsgDto::getForumMsgType), ForumConstants.ForumHandleType.LIKE_COMMENT.getType());
            forumMsgService.deleteOneByParams(params);
        }

    }

    @Override
    public Byte isAuthor(Long authorId, Long userId) {
        if (authorId == null || userId == null) {
            return SystemConstants.NO;
        }
        if (authorId.equals(userId)) {
            return SystemConstants.YES;
        } else {
            return SystemConstants.NO;
        }
    }

    @Override
    public Byte ifLike(Long commentId, Long userId) {
        if (commentId == null || userId == null) {
            return SystemConstants.NO;
        }
        //是否点过赞
        ForumCommentLikeDto forumCommentLikeDto = forumCommentLikeService.selectByCommentAndOperator(commentId, userId);
        if (forumCommentLikeDto != null) {
            return SystemConstants.YES;
        } else {
            return SystemConstants.NO;
        }
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.FORUM_COMMENT_LOCK + "#{#dto.id}"
            }
    )
    public void updateById(ForumCommentDto dto) {
        MongodbUtils.update(
                new Query(
                        Criteria.where(SystemConstants.MONGO_ENTITY_ID_FLAG).is(dto.getId())
                ),
                new Update()
                        .set(LambdaUtil.getFieldName(ForumCommentModel::getContent), dto.getContent())
                        .set(LambdaUtil.getFieldName(ForumCommentModel::getLikeCount), dto.getLikeCount())
                        .set(LambdaUtil.getFieldName(ForumCommentModel::getCommentCount), dto.getCommentCount())
                        .set(LambdaUtil.getFieldName(ForumCommentModel::getDeletedFlag), dto.getDeletedFlag())
                ,
                MongoCollectionConstants.FORUM_COMMENT

        );
    }

    @Override
    public ForumCommentDto selectRootComment(Long commentId) {
        //match
        AggregationOperation matchStage = Aggregation.match(Criteria.where(SystemConstants.MONGO_ENTITY_ID_FLAG).is(commentId));
        //递归查询
        GraphLookupOperation superComment = Aggregation.graphLookup(MongoCollectionConstants.FORUM_COMMENT)
                //起始字段parentId
                .startWith(LambdaUtil.getFieldName(ForumCommentModel::getParentId))
                //连接本文档的起始字段parentId
                .connectFrom(LambdaUtil.getFieldName(ForumCommentModel::getParentId))
                //链接目标文档的id
                .connectTo(SystemConstants.MONGO_ENTITY_ID_FLAG)
                .as("super");
        //super
        ProjectionOperation projectionOperation = Aggregation.project("super").and("super").as("super");
        //unwind
        AggregationOperation unwindStage = Aggregation.unwind("super");
        //replace root
        AggregationOperation replaceRootStage = Aggregation.replaceRoot("super");
        MatchOperation matchOperation = Aggregation.match(Criteria.where("parentId").is(-1));
        LimitOperation limitOperation = Aggregation.limit(1);

        AggregationResults<ForumCommentModel> aggregate = MongodbUtils.aggregate(Aggregation.newAggregation(
                matchStage,
                superComment,
                projectionOperation,
                unwindStage,
                replaceRootStage,
                matchOperation,
                limitOperation
        ), MongoCollectionConstants.FORUM_COMMENT, ForumCommentModel.class);
        List<ForumCommentModel> mappedResults = aggregate.getMappedResults();
        if (CollectionUtils.isNotEmpty(mappedResults)) {
            return CopyUtils.copyObj(mappedResults.get(0), ForumCommentDto.class);
        }
        return null;
    }

    @Override
    public ForumCommentDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                FORUM_COMMENT_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }


    @Override
    public ForumCommentDto selectById(Long id) {
        ForumCommentModel one = MongodbUtils.findOne(id, MongoCollectionConstants.FORUM_COMMENT, ForumCommentModel.class);
        return paddingField(CopyUtils.copyObj(one, ForumCommentDto.class));
    }


    @Override
    public List<ForumCommentDto> commentList(Map<String, Object> params) {
        Request request = Request.configParams(params);
        Criteria criteria = sqlWhere(request.getParams());

        //match
        AggregationOperation matchStage = Aggregation.match(criteria);
        //删除ID的条件
        request.getParams().remove(LambdaUtil.getFieldName(ForumCommentModel::getId));

        //递归查询
        GraphLookupOperation children = Aggregation.graphLookup(MongoCollectionConstants.FORUM_COMMENT)
                //起始字段_id
                .startWith(SystemConstants.MONGO_ENTITY_ID_FLAG)
                //连接本文档的_id
                .connectFrom(SystemConstants.MONGO_ENTITY_ID_FLAG)
                //链接目标文档的parent_id
                .connectTo(LambdaUtil.getFieldName(ForumCommentModel::getParentId))
                //对查询结果进行筛选
                .restrict(sqlWhere(request.getParams()))
                .as("children");
        //将所有的children放在一个数组中
        ProjectionOperation projectionOperation = Aggregation.project("children").and("children").as("children");

        //unwind
        AggregationOperation unwindStage = Aggregation.unwind("children");

        //replace root
        AggregationOperation replaceRootStage = Aggregation.replaceRoot("children");

        // 创建 sort 操作，做先发的在最上面
        SortOperation sortOperation = Aggregation.sort(Sort.Direction.ASC, SystemConstants.MONGO_ENTITY_ID_FLAG);
        // 创建 skip 和 limit 操作
        SkipOperation skipOperation = Aggregation.skip(((long) (request.getPageNo() - 1) * request.getPageSize()));
        LimitOperation limitOperation = Aggregation.limit(request.getPageSize());

        //children是个嵌套数组需要两次unwind然后再replaceRoot
        AggregationResults<ForumCommentModel> aggregate = MongodbUtils.aggregate(Aggregation.newAggregation(
                matchStage,
                children,
                projectionOperation,
                unwindStage,
                replaceRootStage,
                sortOperation,
                skipOperation,
                limitOperation
        ), MongoCollectionConstants.FORUM_COMMENT, ForumCommentModel.class);
        List<ForumCommentModel> mappedResults = aggregate.getMappedResults();

        return mappedResults.stream().map(model -> {
            ForumCommentDto dto = paddingField(CopyUtils.copyObj(model, ForumCommentDto.class));

            //是否是作者
            Long currentUser = request.getLong(ForumConstants.CURRENT_USER);
            if (currentUser != null) {
                dto.setAuthorFlag(isAuthor(dto.getPersonId(), currentUser));
                //是否点过赞
                dto.setLikeFlag(ifLike(dto.getId(), currentUser));
            }

            return dto;
        }).collect(Collectors.toList());

    }

    @Override
    public List<ForumCommentDto> queryList(Map<String, Object> params) {
        Request request = Request.configParams(params);

        Sort.Direction direction = Sort.Direction.ASC;
        //如果指定了排序则按照指定排序 默认是顺序
        String order = request.getString(SystemConstants.SORT_ORDER_RULE_KEY);
        if (StringUtils.isNotBlank(order)) {
            if (SystemConstants.SORT_ORDER_RULE_DESC.equals(order)) {
                direction = Sort.Direction.DESC;
            } else {
                direction = Sort.Direction.ASC;
            }
        }
        return
                MongodbUtils.page(
                        new Query(sqlWhere(params)),
                        request.getPageNo() - 1,
                        request.getPageSize(),
                        Sort.by(direction, SystemConstants.MONGO_ENTITY_ID_FLAG),
                        ForumCommentModel.class,
                        MongoCollectionConstants.FORUM_COMMENT
                ).stream().map(model -> {
                    ForumCommentDto dto = paddingField(CopyUtils.copyObj(model, ForumCommentDto.class));

                    //是否是作者
                    Long currentUser = request.getLong(ForumConstants.CURRENT_USER);
                    if (currentUser != null) {
                        dto.setAuthorFlag(isAuthor(dto.getPersonId(), currentUser));
                        //是否点过赞
                        dto.setLikeFlag(ifLike(dto.getId(), currentUser));
                    }

                    return dto;
                }).collect(Collectors.toList());
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return (int) MongodbUtils.count(new Query(sqlWhere(params)), MongoCollectionConstants.FORUM_COMMENT);
    }

    @Override
    public Long save(ForumCommentDto dto) {
        ForumCommentModel entity = CopyUtils.copyObj(dto, ForumCommentModel.class);
        entity.setId(Snowflake.nextId());
        MongodbUtils.insert(entity, MongoCollectionConstants.FORUM_COMMENT);
        return entity.getId();
    }


    @Override
    public void deleteById(Long id) {
        MongodbUtils.delete(id, MongoCollectionConstants.FORUM_COMMENT);
    }

    @Override
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            MongodbUtils.delete(id, MongoCollectionConstants.FORUM_COMMENT);
        }
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.FORUM_COMMENT_LOCK + "#{#commentId}"
            }
    )
    @Transactional(transactionManager = TransactionManagerConfig.MONGO_TRANSACTION_MANAGER, rollbackFor = RuntimeException.class)
    public void comment(Long commentId, Long userId, Long householdId, String comment) {
        ForumCommentDto forumCommentDto = selectById(commentId);
        //如果评论不存在或者被删除
        if (forumCommentDto == null || SystemConstants.YES.equals(forumCommentDto.getDeletedFlag())) {
            return;
        }
        ForumPostDto forumPostDto = forumPostService.selectById(forumCommentDto.getForumPostId());
        if (forumPostDto == null || SystemConstants.YES.equals(forumPostDto.getDeletedFlag())) {
            return;
        }

        //新增评论
        ForumCommentDto forumCommentCommentDto = new ForumCommentDto();
        forumCommentCommentDto.setForumPostId(forumCommentDto.getForumPostId());
        forumCommentCommentDto.setParentId(forumCommentDto.getId());
        forumCommentCommentDto.setPersonId(userId);
        forumCommentCommentDto.setHouseholdId(householdId);
        forumCommentCommentDto.setCommentedPersonId(forumCommentDto.getPersonId());
        forumCommentCommentDto.setContent(comment);
        forumCommentCommentDto.setCommentTime(new Date());
        forumCommentCommentDto.setId(forumCommentService.save(forumCommentCommentDto));

        //更新评论数量
        forumCommentService.updateCommentCount(forumCommentDto.getId(), ForumConstants.ForumHandleType.COMMENT_COMMENT.getType(), 1);

        //如果不是父级评论,需要更新根评论的评论数量
        if (!forumCommentDto.getParentId().equals(-1L)) {
            ForumCommentDto rootComment = forumCommentService.selectRootComment(forumCommentDto.getId());
            if (rootComment != null) {
                forumCommentService.updateCommentCount(rootComment.getId(), ForumConstants.ForumHandleType.COMMENT_COMMENT.getType(), 1);
            }
        }
        //更新帖子评论数量
        forumPostService.updateForumCount(forumCommentDto.getForumPostId(), ForumConstants.ForumHandleType.COMMENT_COMMENT.getType(), 1);

        //msg和personCount
        forumMsgService.operateSuccessNotify(forumPostDto.getTenantId(), forumCommentCommentDto.getId(), userId, forumCommentDto.getPersonId(), ForumConstants.ForumHandleType.COMMENT_COMMENT.getType());

    }


    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.FORUM_COMMENT_LOCK + "#{#commentId}"
            }
    )
    public void updateCommentCount(Long commentId, Byte handleType, Integer offset) {
        ForumCommentDto forumCommentDto = selectById(commentId);
        if (forumCommentDto == null) {
            return;
        }

        ForumConstants.ForumHandleType byType = ForumConstants.ForumHandleType.getByType(handleType);
        if (byType == null) {
            return;
        }

        Integer count = 0;
        try {
            Field field = ReflectionUtils.findField(ForumCommentDto.class, byType.getFieldName() + "Count");
            if (field != null) {
                field.setAccessible(true);
                count = (Integer) field.get(forumCommentDto);
                count += offset;
                ReflectionUtils.setField(field, forumCommentDto, count <= 0 ? 0 : count);
                ForumCommentService forumCommentService = SpringUtils.getBean(ForumCommentService.class);
                forumCommentService.updateById(forumCommentDto);
            }
        } catch (IllegalAccessException e) {
            log.error(e.getMessage(), e);
        }
    }

}
